package com.sq.partner.manager.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradInsuPlan;
import com.sq.partner.manager.mybatis.model.TradInsuPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanGroup;
import com.sq.partner.manager.mybatis.model.TradProdInst;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.ITradInsuPlanGroupService;
import com.sq.partner.manager.service.ITradPlanGroupService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 组合方案配置
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping("/insureGroupConfig")
public class InsureGroupConfigController {
	
	private static Logger logger = LogUtil.getLog(InsureGroupConfigController.class);

	@Resource
	ITradPlanGroupService groupService;

	@Resource
	ITradInsuPlanGroupService planGroupService;
	
	/**
	 * 跳转至组合方案配置页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String insureDefinition(ModelMap model,HttpServletRequest request) throws Exception {
		List<DictDto> facadeAppTypes = DictCache.getDict(Constants.DICT_FACADE_APP_TYPE);
		//查询投保方式
		model.put("facadeAppTypes",facadeAppTypes);
		return "product/insureGroupConfig/list";
	}
	

	/**
	 * 加载组合方案列表
	 * @param session
	 * @param size
	 * @param current
	 * @param groupName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadInsureGroup")
	public @ResponseBody Page<TradPlanGroup> queryAllInsureGroups(HttpSession session,Integer size,Integer current,String groupName) throws Exception{
		Page<TradPlanGroup> page=new Page<TradPlanGroup>();
		page.setCurrent(current);
		page.setSize(size);
		TradPlanGroup group=new TradPlanGroup();
		//判断空
		group.setGroupName(groupName);
		
		//当前用户所属渠道
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(group);
		Page<TradPlanGroup> page2=groupService.queryPage(page);
		return page2;
	}

	
	/**
	 * 新增方案组
	 * @param req
	 * @param group
	 * @param groupName
	 * @param groupDesc
	 * @param facadeAppType
	 * @param partnerCode
	 * @param groupStatus
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addInsureGroup")
	public @ResponseBody Result addNewInsureGroup(HttpServletRequest req,TradPlanGroup group,String groupName,String groupDesc,String facadeAppType,String partnerCode,String groupStatus) throws Exception{
		if(StrUtil.isEmpty(groupName)){
			return Result.error("组合方案名不能为空");
		}
		if(StrUtil.isEmpty(groupDesc)){
			return Result.error("方案描述不能为空");
		}
		group.setGroupName(groupName);
		group.setGroupDesc(groupDesc);
		group.setFacadeAppType(facadeAppType);
		group.setGroupStatus(groupStatus);
		group.setPartnerCode(partnerCode);
		group.setIsProdGroup("0");
		group.setOperUser(getSessionUser(req).getUserid());
		group.setOperTime(new Date());
		boolean flag = groupService.addTradPlanGroup(group);
		if(flag){
			return Result.success("添加成功");
		}else{
			return Result.error("添加失败");
		}
	}
	
	
	/**
	 * 修改方案组信息
	 * @param req
	 * @param group
	 * @param groupId
	 * @param groupName
	 * @param groupDesc
	 * @param facadeAppType
	 * @param partnerCode
	 * @param groupStatus
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editInsureGroup")
	public @ResponseBody Result editInsureGroup(HttpServletRequest req,TradPlanGroup group,Long groupId,String groupName,String groupDesc,String facadeAppType,String partnerCode,String groupStatus) throws Exception{
		//如果ID没有传入，赋值为-1，避免全表查询更改
		if(null==groupId){
			groupId = (long)-1;
		}
		if(StrUtil.isEmpty(groupName)){
			return Result.error("组合方案名不能为空");
		}
		if(StrUtil.isEmpty(groupDesc)){
			return Result.error("方案描述不能为空");
		}
		group.setGroupId(groupId);
		group.setGroupName(groupName);
		group.setGroupDesc(groupDesc);
		group.setFacadeAppType(facadeAppType);
		group.setGroupStatus(groupStatus);
		group.setPartnerCode(partnerCode);
		group.setOperUser(getSessionUser(req).getUserid());
		group.setOperTime(new Date());
		boolean flag = groupService.editTradPlanGroup(group);
		if(flag){
			return Result.success("修改成功");
		}else{
			return Result.error("修改失败");
		}
	}

	/**
	 * 删除方案组（同时删除该方案组与方案的关联）
	 * @param req
	 * @param groupId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delInsureGroup")
	public @ResponseBody Result deleteInsureGroup(HttpServletRequest req,Long groupId) throws Exception{
		//如果ID没有传入，赋值为-1，避免全表查询更改
		if(null==groupId){
			groupId = (long)-1;
		}

		boolean flag = groupService.deleteTradPlanGroup(groupId);
		if(flag){
			planGroupService.deleteTradInsuPlanGroupByGroupId(groupId);
			return Result.success("删除成功");
		}else{
			return Result.error("删除失败");
		}
	}
	
	
	/**
	 * 查询方案组对应合作伙伴下所有投保方案信息
	 * @param session
	 * @param size
	 * @param current
	 * @param groupId
	 * @param insuPlanNo
	 * @param insuPlanName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadInsurePlans")
	public @ResponseBody Page<TradInsuPlan> queryAllInsurePlans(HttpSession session,Integer size,Integer pageIndex,Long groupId,String partnerCode,String insuPlanNo,String insuPlanName) throws Exception{
		
		
		Page<TradInsuPlan> page=new Page<TradInsuPlan>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		if(null == groupId){
			page.setMessage("方案组ID不能为空");
			page.setResult("error");
			return page;
		}
		
		TradInsuPlan plan=new TradInsuPlan();
		//判断空
		plan.setInsuPlanNo(insuPlanNo);
		plan.setInsuPlanName(insuPlanName);
		
		page.setType(plan);
		Page<TradInsuPlan> page2=groupService.queryTradInsuPlanPage(page,groupId,partnerCode);
		return page2;
	}
	

	/**
	 * 查询某个方案组里，已配置的所有方案
	 * @param plangroup
	 * @param planGroupId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadInsuPlanGroups")
	public @ResponseBody List<TradInsuPlanGroup> queryInsuPlanGroups(TradInsuPlanGroup plangroup,String planGroupId) throws Exception{
		plangroup.setPlanGroupId(planGroupId);
		List<TradInsuPlanGroup> list = planGroupService.queryTradInsuPlanGroup(plangroup);
		return list;
	}

	
	/**
	 * 方案管理配置
	 * @param groupMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/setInsuPlanGroupRelation")
	public @ResponseBody Result setRelation(@RequestBody Map[] groupMap) throws Exception {
		/**
		 * 循环判断：
		 * 一、如果该方案被选中，查询其是否已存在于方案组关联表中
		 * 存在：则更新”是否必需“，不存在：将该方案维护到方案组关联表中，并删除其原先与方案组的关联。
		 * 
		 * 二、如果该方案未选中，查询其是否已存在于方案组关联表中
		 * 存在：删除该关联数据，不存在：无操作。
		 * 注：变量checkflag：1 选中，2 未选中。
		 */
		for(int i=0;i<groupMap.length;i++){
			String checkflag = groupMap[i].get("isChecked").toString();
			//选中
			String groupid = groupMap[i].get("planGroupId").toString();		//方案组id
			String insuNo = groupMap[i].get("insuPlanNumber").toString();	//方案号
			String req = groupMap[i].get("required").toString();			//是否必需
			
			TradInsuPlanGroup planGroup = new TradInsuPlanGroup();
			planGroup.setInsuPlanNumber(insuNo);
			planGroup.setPlanGroupId(groupMap[i].get("planGroupId").toString());
			
			List<TradInsuPlanGroup> list = planGroupService.queryTradInsuPlanGroup(planGroup);

			TradInsuPlanGroup gp1 = new TradInsuPlanGroup();
			gp1.setPlanGroupId(groupid);
			gp1.setInsuPlanNumber(insuNo);
			gp1.setRequired(req);

			//选中
			if("1".equals(checkflag)){
				//不存在
				if(list.size()==0){
					
					planGroupService.deleteTradInsuPlanGroup(insuNo);
					
					planGroupService.addTradInsuPlanGroup(gp1);
				}else{
					//存在
					planGroupService.updateIsRequired(gp1);
				}
				//未选中
			}else{
				//存在
				if(list.size()==1){
					planGroupService.deleteTradInsuPlanGroup(gp1);
				}
			}
		}
		
		return Result.success("配置成功");
	}
	
	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}
}
